//
//  ViewController.m
//  17-HomeWork(通讯录)
//
//  Created by ParkourH on 16/8/6.
//  Copyright © 2016年 ParkourH. All rights reserved.
//

#import "ViewController.h"
#import "Contact.h"
#import "MyTableViewCell.h"
#import "VCOfAddContact.h"
#import "VCOfDetails.h"
@interface ViewController () <UITableViewDelegate, UITableViewDataSource, AddContactDelegate, SaveContentDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIBarButtonItem *barButtonOfEdit;
@property (nonatomic, strong) NSMutableArray *mArrOfContract;

@property (nonatomic, strong) NSMutableDictionary *mDicOfContact;

@property (nonatomic, strong) NSMutableArray<NSIndexPath *> *mArrOfSelectIndex;
@property (nonatomic, strong) NSMutableIndexSet *mSet;

// 保存联系人信息的坐标(待会儿传回来要交换)
@property (nonatomic, strong) NSIndexPath *indexPath;

@property (nonatomic, copy) NSString *pathOfContact;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
//    [self.barButtonOfEdit setAction:@selector(editAction)];
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self handleData];
}

- (void)handleData {

    self.mArrOfSelectIndex = [NSMutableArray array];
    self.mSet = [NSMutableIndexSet indexSet];
    self.mArrOfContract = [NSMutableArray array];
    
    NSString *pathOfDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    self.pathOfContact = [pathOfDocuments stringByAppendingPathComponent:@"contact.plist"];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:self.pathOfContact]) {
    
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"DLS160710(1)" ofType:@"plist"];
    NSArray *array = [NSArray arrayWithContentsOfFile:path];

    for (NSDictionary *dictionary in array) {
        
//        NSString *str = [[[dictionary objectForKey:@"name"] substringToIndex:1] uppercaseString];
//        NSLog(@"%@", str);
        Contact *contact = [[Contact alloc] init];
        [contact setValuesForKeysWithDictionary:dictionary];
        [self.mArrOfContract addObject:contact];
        
        }
    
    BOOL isSuccess = [NSKeyedArchiver archiveRootObject:self.mArrOfContract toFile:_pathOfContact];
    if (isSuccess) {
        NSLog(@"success");
    } else {
    
        NSLog(@"fail");
    }
    }
    else {
    
    self.mArrOfContract = [NSKeyedUnarchiver unarchiveObjectWithFile:self.pathOfContact];
    }
}

#pragma mark ------------  DataSource  -----------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _mArrOfContract.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    
    Contact *contact = self.mArrOfContract[indexPath.row];
    [cell setContact:contact];
    
    return cell;
}

#pragma mark ------------  delegate  -----------
/** 返回cell的编辑状态样式 */
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
/** 选中 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    self.indexPath = indexPath;
    if (self.editing) {
        
        [self.mArrOfSelectIndex addObject:indexPath];
        [self.mSet addIndex:indexPath.row];
        return;
    }
    
}
/** 反选 */
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (self.editing) {
        
        [self.mArrOfSelectIndex removeObject:indexPath];
        [self.mSet removeIndex:indexPath.row];
    }
}
/** segue的方法 */
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    
    if ([sender isKindOfClass:[MyTableViewCell class]]) {
        
        MyTableViewCell *cell = sender;
        VCOfDetails *vc = segue.destinationViewController;
        vc.contact = cell.contact;
        vc.delegate = self;
        
    } else if ([sender isKindOfClass:[UIBarButtonItem class]]) {
    
        VCOfAddContact *vc = segue.destinationViewController;
        vc.delegate = self;
    }
}

#pragma mark ------------  add Delegate  -----------
- (void)addContact:(Contact *)contact {
    
    [self.mArrOfContract addObject:contact];
    [self.tableView reloadData];
    BOOL isContactWriteSuccess = [NSKeyedArchiver archiveRootObject:_mArrOfContract toFile:self.pathOfContact];
    
    if (isContactWriteSuccess) {
        
        NSLog(@"写入联系人成功");
    } else {
        
        NSLog(@"写入联系人失败");
    }
    NSLog(@"%@", self.pathOfContact);
}

/** 让tableView进入编辑状态 */
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {

    [super setEditing:editing animated:animated];
    [_tableView setEditing:editing animated:animated];
    
    if (editing) {
        
      
    } else {
    
        // 删除数据源
        [self.mArrOfContract removeObjectsAtIndexes:_mSet];
        
        if (_mSet.count != 0) {
            
            BOOL isSuccess = [NSKeyedArchiver archiveRootObject:self.           mArrOfContract toFile:_pathOfContact];
            if (isSuccess) {
                NSLog(@"删除成功");
            } else {
            
                NSLog(@"删除失败");
            }
        
            // 删除cell
            [_tableView deleteRowsAtIndexPaths:_mArrOfSelectIndex withRowAnimation:UITableViewRowAnimationAutomatic];
        
            [_mArrOfSelectIndex removeAllObjects];
            [_mSet removeAllIndexes];
            
        }
    }
}

#pragma mark ------------  save delegate  -----------
- (void)save:(Contact *)contact {
    
//    [self.mArrOfContract addObject:contact];
    [self.mArrOfContract replaceObjectAtIndex:self.indexPath.row withObject:contact];
    [self.tableView reloadData];
    
    BOOL isSuccess = [NSKeyedArchiver archiveRootObject:self.           mArrOfContract toFile:_pathOfContact];
    if (isSuccess) {
        NSLog(@"修改成功");
    } else {
        
        NSLog(@"修改失败");
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
